package com.ivo.activiti.bpmn.record;

import com.ivo.activiti.hr.entity.Department;
import com.ivo.activiti.hr.entity.Employee;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author wj
 * @version 1.0
 */
@Service
public class RecordService {

    @Resource
    private ExecutionRepository executionRepository;

    @Resource
    private HistoryRepository historyRepository;

    @Resource
    private AssigneeService assigneeService;

    public void createExecution(String task, String orderNumber, String node) {
        List<Actor> actorList = assigneeService.getActor(node);
        if(actorList.size() == 0) actorList.add(new Actor(new Department(), new Employee()));
        for(Actor actor : actorList) {
            createExecution(task, orderNumber, node, actor.getEmployee().getEmployee_ID());
        }
    }

    public void createExecution(String task, String orderNumber, String node, String handler) {
        Execution execution = new Execution();
        execution.setId(UUID.randomUUID().toString());
        execution.setTask(task);
        execution.setOrderNumber(orderNumber);
        execution.setNode(node);
        execution.setHandler(handler);
        execution.setCreateDate(new Date());
        executionRepository.save(execution);
        createHistory(execution);
    }

    void createHistory(Execution execution) {
        History history = new History();
        history.setId(execution.getId());
        history.setOrderNumber(execution.getOrderNumber());
        history.setNode(execution.getNode());
        history.setHandler(execution.getHandler());
        history.setCreateDate(execution.getCreateDate());
        history.setHandleDate(null);
        historyRepository.save(history);
    }

    public List<Execution> getExecution(String task) {
        return executionRepository.findByTask(task);
    }

    public void completeTask(String task) {
        List<Execution> executionList = getExecution(task);
        executionList.get(0).setHandleDate(new Date());
        for(Execution execution : executionList) {
            deleteExecution(execution);
        }
    }

    public void deleteExecution(Execution execution) {
        History history = historyRepository.findById(execution.getId()).orElse(null);
        if(execution.getHandleDate() != null) {
            history.setHandleDate(execution.getHandleDate());
            historyRepository.save(history);
        } else {
            historyRepository.delete(history);
        }
        executionRepository.delete(execution);
    }
}
